<template>
<a-spin :spinning="confirmLoading">
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery1">
        <a-row :gutter="24">
          <a-col :xl="3" :lg="7" :md="8" :sm="24">
            <a-form-item label="状态">
              <a-select v-model="queryParam.bizStatus" allowClear>
                <a-select-option v-for="(item, index) in bizStatus" :key="index" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="收货门店">
              <a-cascader :options="departModel.departTreeOptions" :showSearch="true" expand-trigger="hover"
                placeholder="" :fieldNames="departModel.fieldNames" style="width: 210px"
                v-model="queryParam.selecteddeparts" @change="handleDepartChange" />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="品牌">
              <a-select allowClear defaultValue="1" v-model="queryParam.brandCode" showSearch
                :filter-option="filterOption" :not-found-content="null">
                <a-select-option v-for="item in brandList" :key="item.id" :value="item.brandCode">
                  {{ item.brandName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="发货日期">
              <a-range-picker
                :ranges="{ 今天: [moment(), moment()], 近7天:[moment().subtract(7, 'days'),moment()],本月: [moment().startOf('month'), moment().endOf('month')] }"
                v-model="deliverDateRange"
                @change="handleDeliverChange"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="签收日期">
              <a-range-picker
                :ranges="{ 今天: [moment(), moment()], 近7天:[moment().subtract(7, 'days'),moment()],本月: [moment().startOf('month'), moment().endOf('month')] }"
                v-model="signDateRange"
                @change="handleSignChange"
              />
            </a-form-item>
          </a-col>
          
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="发货单号">
              <a-input v-model="queryParam.billNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="SKU编码">
              <a-input v-model="queryParam.itemSku" allowClear></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery1" icon="search">查询</a-button>
              <a-button type="default" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator" v-has="'posIoBill:batchSign'">
      <a-button :disabled="queryParam.bizStatus != 0" style="margin-left: 8px" type="primary" @click="handleBatchAudit">
        批量签收
      </a-button>
    </div>
    <!-- table区域-begin -->
    <div>
      <a-table ref="table" size="middle" bordered rowKey="billNo" :columns="columns" :dataSource="dataSource"
        :pagination="ipagination" :loading="loading" class="j-table-force-nowrap"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <template v-if="record.bizStatus === 0">
            <a-divider type="vertical" />
            <a-popconfirm title="确定作废吗?" @confirm="() => handleStatus(record.billId, -1)">
              <a>作废</a>
            </a-popconfirm>
          </template>
        </span>
        <span slot="bizStatus" slot-scope="text">
          <a-tag color="blue" v-if="text === 1">已签收</a-tag>
          <a-tag color="orange" v-if="text === 0">待签收</a-tag>
          <a-tag color="red" v-if="text === -1">作废</a-tag>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <posStockIoBill-modal ref="modalForm" @ok="modalFormOk"></posStockIoBill-modal>
  </a-card>
  </a-spin>
</template>

<script>
import '@/assets/less/TableExpand.less'
import PosStockIoBillModal from './modules/PosStockIoBillModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { postAction } from '@/api/manage'
import { queryDepartTreeList1, queryMerchantBussList } from '@/api/api'
import { Modal } from 'ant-design-vue'
import moment from 'moment'

export default {
  name: 'PosStockIoBillList',
  mixins: [JeecgListMixin],
  components: {
    PosStockIoBillModal,
  },
  data() {
    return {
      description: '入库单管理页面',
      disableMixinCreated: true,
      confirmLoading: false,
      deliverDateRange: [],
      signDateRange: [],
      moment,
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' },
        selectedOptions: [],
      },
      brandList: [
      ],
      // 表头
      columns: [
        {
          title: '发货机构',
          align: 'center',
          dataIndex: 'senderStockOrgNm',
        },
        {
          title: '收货门店',
          align: 'center',
          dataIndex: 'receiverStockOrgNm',
        },
        {
          title: '发货单号',
          align: 'center',
          dataIndex: 'billNo',
        },
        {
          title: '发货日期',
          align: 'center',
          dataIndex: 'sendDate',
          sorter: true,
        },
        {
          title: '总件数',
          align: 'center',
          dataIndex: 'totalQty',
        },
        {
          title: '总金额',
          align: 'center',
          dataIndex: 'totalAmount',
        },
        {
          title: '品牌',
          align: 'center',
          dataIndex: 'brandName'
        },
        {
          title: '签收日期',
          align: 'center',
          dataIndex: 'billDate',
          sorter: true,
        },
        {
          title: '经办人',
          align: 'center',
          dataIndex: 'clerkUser',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'bizStatus',
          scopedSlots: { customRender: 'bizStatus' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      bizStatus: [
        { text: '待签收', value: '0' },
        { text: '已签收', value: '1' },
        { text: '作废', value: '-1' },
      ],
      url: {
        list: '/stock/posStockIoBill/list',
        changeStatus: '/stock/posStockIoBill/changeStatus',
        batchPackageCheckIn2: '/stock/posStockIoBill/batchPackageCheckIn2',
      },
    }
  },
  computed: {},
  created() {
    console.log('---created1---')
    this.$set(this.queryParam, 'bizStatus', '0')
    this.loadDepartTree()
    this.searchQuery1()
    this.loadBrandList()
  },
  methods: {
    assembleQueryParam() {
      console.log(this.departModel.selectedOptions)
      if (!this.queryParam.selecteddeparts) {
        return
      }

      let selectedOptions = this.departModel.selectedOptions
      if (selectedOptions && selectedOptions.length == 2) {
        this.queryParam.senderStockOrgCd = selectedOptions[0].orgCode
        this.queryParam.shopId = selectedOptions[1].value === '0' ? null : selectedOptions[1].value
      } else {
        this.queryParam.senderStockOrgCd = null
        this.queryParam.shopId = null
      }
    },
    loadBrandList() {
      this.brandList = []
      queryMerchantBussList({ 'bussType': 'BRAND' }).then((res) => {
        if (res.success) {
          for (let a of res.result) {
            this.brandList.push({ brandName: a.bussName, brandCode: a.bussCode })
          }
        }
      })
    },
    searchReset1(){
      this.queryParam = {}
      this.deliverDateRange = []
      this.signDateRange = []
      this.searchQuery1()
    },
    handleDeliverChange(date, dateString) {
      this.queryParam.beginDeliveryTime = dateString[0]
      this.queryParam.endDeliveryTime = dateString[1]
    },
    handleSignChange(date, dateString) {
      this.queryParam.beginSignTime = dateString[0]
      this.queryParam.endSignTime = dateString[1]
    },
    handleDepartChange(value, selectedOptions) {
      console.log('value=', value, 'selectedOptions=', selectedOptions)
      this.departModel.selectedOptions = selectedOptions
    },
    searchQuery1() {
      this.assembleQueryParam()
      this.loadData(1)
    },
    handleBatchAudit() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择记录')
        return false
      }

      if (this.selectedRowKeys.length > 30) {
        this.$message.warning('单次最多支持30条')
        return false
      }

      let that = this
      Modal.confirm({
        title: '确定签收吗?',
        okText: '确定',
        okType: 'warning',
        cancelText: '取消',
        onOk() {
          console.log('OK')
          that.doSign()
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    doSign() {
      console.log(this.selectedRowKeys)
      let billNos = this.selectedRowKeys.join(',')
      let key = 'myxp@1234'
      this.confirmLoading = true
      postAction(this.url.batchPackageCheckIn2 + '?billNos='+billNos+'&key='+key, null).then((res) =>{
        if(res.success){
          this.$message.success('操作成功')
        }else{
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
        this.onClearSelected()
        this.loadData()
      })
    },
    loadDepartTree() {
      queryDepartTreeList1().then((res) => {
        if (res.success) {
          let departList = res.result
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach((x) => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })
        }
      })
    },
    handleDetail(record) {
      this.$refs.modalForm.view(record)
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = false
    },
    handleStatus(billId, bizStatus) {
      let param = {
        billId: billId,
        bizStatus: bizStatus
      }
      postAction(this.url.changeStatus, param).then((res) => {
        if (res.success) {
          this.$message.info('操作成功')
          this.loadData()
        } else {
          this.$message.warn(res.message)
        }
      })
    }
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>